#include "GnApplicationPCH.h"
#include "GnApp.h"
#include "GnDX9Constructor.h"

GnInstance GnApp::msWindowInstance = NULL;
GnApp* GnApp::msSingletone = NULL;

GnApp::GnApp(const gtchar* windowCaption, guint width,
			 guint height, bool useFrameSystem,
			 guint menuID, guint bitDepth,
			 gulong windowStyle)
{
	mpAppWindow = GnNew GnAppWindow( windowCaption, menuID, width, height, windowStyle );
	GnAssert(!msSingletone);
	msSingletone = this;
}

GnApp::~GnApp()
{
	GnDelete mpAppWindow;
	GnDelete mpRenderer;
}

bool GnApp::CreateGnWindow(int nCmdShow, GnInstance instance, GnWindowHandle parentHandle)
{
	return mpAppWindow->CreateGnWindow(nCmdShow, instance, parentHandle);
}
bool GnApp::CreateRenderer()
{
	mpRenderer = GnDX9Constructor::CreateRenderer( mpAppWindow );
	return true;
}
bool GnApp::Init()
{
	ResetTimes();
	return true;
}
void GnApp::MainLoop()
{
	/*if (!MeasureTime())
		return;*/
MeasureTime();
	BeginUpdate();
	UpdateFrame();
	EndUpdate();

	BeginFrame();
	RenderFrame();
	EndFrame();
}
bool GnApp::MeasureTime()
{
	// start performance measurements
	if (mLastTime == -1.0f)
	{
		mLastTime = GnGetCurrentTimeInSec();
		mAccumTime = 0.0f;
		mClicks = 0;
	}

	// measure time
	mCurrentTime = GnGetCurrentTimeInSec();
	float deltaTime = mCurrentTime - mLastTime;

	if (deltaTime < 0.0f)
		deltaTime = 0.0f;
	mLastTime = mCurrentTime;
	mAccumTime += deltaTime;

	// frame rate limiter
	if (mAccumTime < (mLastFrame + mMinFramePeriod))
		return false;

	mFrameTime = mAccumTime - mLastFrame;
	mLastFrame = mAccumTime;
	return true;
}

void GnApp::UpdateFrame()
{

}

void GnApp::CullFrame()
{

}

void GnApp::RenderFrame()
{
	mpRenderer->BeginFrame();
	mpRenderer->EndFrame();
	mpRenderer->DisplayFrame();
}

